package com.myalibaba.web;
import com.myalibaba.example.MyService;
import com.myalibaba.example.RedisDistributedLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
public class WebController {

    @Autowired
    private MyService userService;
    @Autowired
    private RedisDistributedLock redisDistributedLock;

    @RequestMapping("druidTest")
    public String druidTest() {
        userService.druidTest();
        return "druidTest successfully";
    }

    @GetMapping("lock/{resourceId}")
    public String lockResource(@PathVariable String resourceId) {
        if (redisDistributedLock.lock(resourceId)) {
            try {
                // 在这里执行需要加锁的代码块
                System.out.println(resourceId);
                return "Resource " + resourceId + " locked";
            } finally {
                redisDistributedLock.unlock(resourceId); // 确保最终释放锁
            }
        } else {
            return "Failed to lock resource " + resourceId;
        }
    }

    @RequestMapping("createUser")
    public String createUser(@RequestParam String name, @RequestParam String email) {
        userService.insertUser(name, email);
        return "User inserted successfully";
    }


    @RequestMapping("updateUser")
    public String updateUser() {
        userService.updateUser();
        return "User updateed successfully";
    }

    @RequestMapping("getAllUsers")
    public List<Map<String, Object>> getAllUsers() {
        return userService.getAllUsers();
    }
}
